package com.flca.dbs.berkeley;

import java.util.HashMap;
import java.util.Map;

import com.flca.frw.dao.RegisterDatabase;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.Transaction;

public class BerkeleyDaoHelper extends DaoHelperBerkeleyBase {

	private RegisterDatabase regDbs;
	private Environment environment;
	private Map<String, Database> databaseMap;

	BerkeleyDaoHelper(RegisterDatabase aRegDbs)
	{
		regDbs = aRegDbs;
		fillDatabasenames();
		setup();
	}
	
	protected Environment getEnvironment() {
		return environment;
	}
	
	protected Map<String, Database> getDatabases() {
		return databaseMap;
	}
	
	protected String getDatabaseDir() {
		return regDbs.getUrl();
	}
	
	protected Transaction getTransaction() {
		try {
			return environment.getThreadTransaction();
		} catch (DatabaseException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	protected void setData(Environment aEnv, Map<String, Database> aDbsMap) 
	{
		environment = aEnv;
		databaseMap = aDbsMap;
	}
	
	/**
	 * this will use the dbname property value to prefill the database map
	 * the dbsname property can be a comma seperated list of names that correspond with the Simple classname (eg dbname=Customer.Adress,Product)
	 * <br>or the dbname contains the fully qual classname of the class that implements IBerkelerDbsNamesProvider
	 */
	private void fillDatabasenames() 
	{
		databaseMap = new HashMap<String, Database>();
		
		if (regDbs.getUnitName() != null && regDbs.getUnitName().trim().length() > 0) {
			if (regDbs.getUnitName().indexOf(".") > 0) {
				try {
					Class<?> cls = Class.forName(regDbs.getUnitName());
					IBerkeleyDbsNamesProvider dbsprov = (IBerkeleyDbsNamesProvider)  cls.newInstance();
					for (String dbname : dbsprov.getDatabaseNames()) {
						databaseMap.put(dbname, null);
					}
				} catch (Exception e) {
					String msg = "Property dbsname (" + regDbs.getUnitName() + ") is not a valid IBerkelerDbsNamesProvider";
					throw new RuntimeException(msg, e);
				}
			} else {
				String tokens[] = regDbs.getUnitName().split(",");
				for (int i = 0; i < tokens.length; i++) {
					databaseMap.put(tokens[i], null);
				}
			}
		} else {
			String msg = "Property dbsname is null or empty";
			throw new RuntimeException(msg);
		}
	}
}
